package com.study.SpringBootLesson4;

import com.study.SpringBootLesson4.springboot.filter.MyFilter2;
import com.study.SpringBootLesson4.springboot.listener.MyServletRequestListener2;
import com.study.SpringBootLesson4.springboot.servlet.MyServlet2;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;

import javax.servlet.DispatcherType;

@SpringBootApplication
@ServletComponentScan(basePackages = {
		"com.study.SpringBootLesson4.servlet",
		"com.study.SpringBootLesson4.filter",
		"com.study.SpringBootLesson4.jsp",
		"com.study.SpringBootLesson4.listener",})
public class SpringBootLesson4Application extends SpringBootServletInitializer {

	public static void main(String[] args) {
		SpringApplication.run(SpringBootLesson4Application.class, args);
	}

	/**
	 * 在Application中注册Servlet
	 */
	@Bean
	public static ServletRegistrationBean servletRegistrationBean () {

		ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean();
		servletRegistrationBean.setServlet(new MyServlet2());
		servletRegistrationBean.setName("myServlet2");
		servletRegistrationBean.addUrlMappings("/spring-boot/myServer2");
		servletRegistrationBean.addInitParameter("myKey", "myValue");

		return servletRegistrationBean;
	}

	/**
	 * 在Application中注册过滤器
	 */
	@Bean
	public static FilterRegistrationBean filterRegistrationBean() {

		FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
		filterRegistrationBean.setFilter(new MyFilter2());
		filterRegistrationBean.addServletNames("myServlet2");
//		filterRegistrationBean.addUrlPatterns("/spring-boot/myServer2");
		filterRegistrationBean.setDispatcherTypes(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.INCLUDE);

		return filterRegistrationBean;
	}

	/**
	 * 在Application中注册监听器
	 */
	@Bean
	public static ServletListenerRegistrationBean servletListenerRegistrationBean() {

		ServletListenerRegistrationBean servletListenerRegistrationBean = new ServletListenerRegistrationBean();
		servletListenerRegistrationBean.setListener(new MyServletRequestListener2());

		return servletListenerRegistrationBean;
	}

	@Override
	protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
		builder.sources(SpringBootLesson4Application.class);
		return builder;
	}
}
